package com.sites.api;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.sites.common.SiteInfo;
import com.sites.common.model.Article;
import com.sites.common.model.Column;

import java.util.List;

public class ApiService {

    private Article artDao = new Article().dao();
    private Column colDao = new Column().dao();

    /**
     * 根据栏目标识（英文名）获取栏目信息
     * @param enName
     * @return
     */
    public Column getColumnByEnName(String enName){
        String sql = colDao.getSql("api.getColumnByEnName");
        return colDao.findFirst(sql, enName, SiteInfo.siteId);
    }

    /**
     * 分页查询栏目文章
     * @param page		页码
     * @param limit		每页显示条数
     * @param column	栏目id
     * @return
     */
    @SuppressWarnings("unchecked")
    public Page<Article> queryArtsPage(int page, int limit, int column){
        Kv kv = Kv.create();
        kv.put("siteId", SiteInfo.siteId);
        kv.put("column", column);
        return artDao.template("api.queryArtsPage", kv).paginate(page, limit);
    }

    /**
     * 分页查询栏目(支持多个)文章
     * @param page		页码
     * @param limit		每页显示条数
     * @param cols	    栏目英文标示，支持多个逗号分割
     * @return
     */
    @SuppressWarnings("unchecked")
    public Page<Article> queryArtsPagePro(int page, int limit, String cols){
        Kv kv = Kv.create();
        kv.put("siteId", SiteInfo.siteId);
        kv.put("columns", cols.split(","));
        return artDao.template("api.queryArtsPagePro", kv).paginate(page, limit);
    }

    /**
     * 根据文章id获取文章内容
     * @param id
     * @return
     */
    public Article getArtById(int id){
        String sql = artDao.getSql("api.getArtById");
        return artDao.findFirst(sql, id);
    }

    /**
     * 根据栏目id获取子栏目及子栏目文章列表
     * @param colId
     * @return
     */
    public List<Column> getColsAndArts(int colId, int orderType){
        String sql = colDao.getSql("api.getColsByParentId");

        List<Column> columnList = colDao.find(sql, colId);
        for(Column column : columnList){
            Kv kv = Kv.of("col", column.getId()).set("orderType", orderType);
            SqlPara artSql = artDao.getSqlPara("api.getArtsByColId", kv);
            List<Article> articleList = artDao.find(artSql);
            column.put("arts", articleList);
        }

        return columnList;
    }

}
